# coding: utf8

from ops.chatbot.utils.send_msg import SendMessage
from ops.devops.utils.util_config import get_config
from ops.devops.models import Module
from ops.devops.utils.utils_cdn import CreateClient, CdnOp
from ops.chatbot.utils.utils import get_kv_by_list
import json


# 初始化client
conf = get_config('cloud')


# ref命令时执行如下函数
def ref(*args, **kwargs):
    """
    刷新cdn缓存，cdn地址在settings_prod.py中
    :param args:
    :param kwargs:
    :return:
    """

    # all_projects = get_projects()

    webhook = kwargs.get("webhook")
    project_list = args
    msg_list = []
    msg = f'debug1:输入信息{args}'
    print(msg)

    # 根据输入信息判断并刷新缓存
    for string_input in project_list:
        # 以-分割传入的参数，取项目名和环境,分割后长度为1则取pre环境
        project_info = string_input.split('-')

        # 判断，默认env为pre
        if len(project_info) > 1:
            alias_name, env = project_info[0:2]
        else:
            alias_name, env = project_info[0], 'pre'
        # 参数help时，返回帮助并跳过本次循环
        if alias_name == 'help':
            msg = '刷新阿里云cdn缓存，用法: ref project1-env1 project2-env2 project3-env3 ...'
            msg_list.append(msg)
            continue
        params = Module.objects.get(alias_name=alias_name).params
        domain = json.loads(params).get(env).get('domain')
        if not domain:
            msg = "未获取到项目别名{0}的cdn域名配置，请检查".format(alias_name)
            msg_list.append(msg)
            continue
        try:
            client = CreateClient.create_client(conf.get('cloud_type'), conf.get('access_id'),
                                                conf.get('access_secret'))
            res = CdnOp.refresh_dcdn(client, domain, conf.get('object_type', 'directory'))

            if res.get('code') != 200:
                msg = '项目别名:{0}，环境：{1}【{2}】的cdn缓存刷新失败，原因：{3}{4}'.format(alias_name, env, domain, res.get('code'), res.get('msg'))
            else:
                msg = '已刷新项目别名:{0}，环境：{1}【{2}】的cdn缓存，请验证'.format(alias_name, env, domain)
        except Exception as e:
            msg = '刷新项目别名:{0}，环境：{1}【{2}】的cdn缓存失败，请检查'.format(alias_name, env, domain)
        msg_list.append(msg)

    messages = '\n'.join(msg_list)
    SendMessage.send_md(webhook, messages)


# 输入cdn命令时执行如下函数
def cdn(*args, **kwargs):
    """
    增加cdn域名和配置
    :param args:
    :param kwargs:
    :return:
    """

    webhook = kwargs.get("webhook")
    domain_list = args
    msg_list = []
    msg = f'debug:输入信息{args}'
    print(msg)

    # 根据输入信息判断并刷新缓存
    for domain in domain_list:
        # 以-分割传入的参数，取项目名和环境,分割后长度为1则取pre环境

        # 参数help时，返回帮助并跳过本次循环
        if domain == 'help':
            msg = '添加cdn域名，用法: cdn domain1 domain2 ...'
            msg_list.append(msg)
            continue

        try:
            client = CreateClient.create_client(conf.get('cloud_type'), conf.get('access_id'),
                                                conf.get('access_secret'))

            # 创建域名
            CdnOp.create_domain(client, domain, conf.get('cdn_sources'), conf.get('business_type', 'web'), conf.get('service_area', 'mainland_china'), conf.get('origin_type', 'ipaddr'))

            # 查询域名cname
            cname_list = get_kv_by_list(CdnOp.list_domains(client), 'domain_name', 'cname')
            # 修改https配置
            CdnOp.update_https_info(client, conf.get('cert_name'), domain)
            msg = '已增加域名={0}的cdn配置，回源地址为{1}，cname为:{2}请关注！'.format(domain, conf.get('cdn_sources'), cname_list.get(domain))
        except Exception as e:
            msg = '增加域名={0}的cdn配置失败，请检查！原因:{1}'.format(domain, e)
        msg_list.append(msg)

    messages = '\n'.join(msg_list)
    SendMessage.send_md(webhook, messages)
